<template>
  <van-nav-bar
    title="医生详情"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
    fixed
  />
  <div class="doctor-info">
    <img :src="doctor.avatar" alt="Doctor" />
    <div class="doctor-details">
      <h3>
        {{ doctor.name }} <span class="badge">{{ doctor.title }}</span>
      </h3>
      <div class="department">{{ doctor.department }}</div>
      
      <button
        :class="{ 'follow-button': true, followed: isFollowed }"
        @click="followDoctor"
      >
        {{ isFollowed ? "取消关注" : "+关注" }}
      </button>
    </div>
  </div>
  <div class="doctor-intro">
    {{ doctor.intro }}
  </div>
  <div class="appointment">
    <h4>医院门诊预约</h4>
    <div class="app">
      <table class="schedule-table">
        <thead>
          <tr>
            <th v-for="(date, index) in dates" :key="index">
              {{ date.formattedDate }}<br />
              <span class="weekday">{{ date.weekday }}</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td v-for="(date, index) in dates" :key="index" style="padding: 12px;">
              <van-button
                :type="date.hasAvailableSlot ? 'primary' : 'default'"
                :disabled="!date.hasAvailableSlot"
                @click="bookAppointment(date, index)"
                round
                block
              >
                {{ date.hasAvailableSlot ? "预约" : "无号" }}
              </van-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <!-- 就诊人选择弹出层 -->
  <van-popup v-model:show="showPatientSelector" position="bottom" round>
    <div class="patient-selector">
      <div class="popup-title">选择就诊人</div>
      <van-cell-group>
        <van-cell
          v-for="patient in patientList"
          :key="patient.medicalRecordNumber"
          :title="patient.patientName"
          :label="`${patient.gender} ${patient.age}岁`"
          clickable
          @click="selectPatient(patient)"
        />
      </van-cell-group>
    </div>
  </van-popup>

  <!-- 时间段选择弹出层 -->
  <van-popup v-model:show="showTimeSlots" position="bottom" round>
    <div class="time-slots">
      <div class="popup-title">选择就诊时间</div>
      <van-cell-group>
        <van-cell
          v-for="slot in timeSlots"
          :key="slot.id"
          :title="slot.time"
          :label="`挂号费：¥${slot.price} | 剩余号源：${slot.remaining}`"
          clickable
          @click="selectTimeSlot(slot)"
        />
      </van-cell-group>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Button as VanButton, NavBar as VanNavBar, showToast } from "vant";
import { useUserStore } from "../stores/user.js";
import { useRouter, useRoute } from "vue-router";
import { useDoctorFollowStore } from "../stores/doctorFollowStore.js";
import { getDoctorByWorkId, getNextWeekSchedules } from "../api/doctor/doctorRequest.js";
import { getPatientInfoAPI } from "../api/user/user.js";
import { bookingAPI } from "../api/book/bookRequest.js";
import { addFollowAPI, deleteFollowAPI, isFollowedAPI } from "../api/follow/follow.js";

const userStoreAPI = useUserStore();
const router = useRouter();
const route = useRoute();
const doctorFollowStore = useDoctorFollowStore();
const showPatientSelector = ref(false);
const patientList = ref([]);
const selectedPatient = ref(null);
const showTimeSlots = ref(false);
const timeSlots = ref([]);
const selectedTimeSlot = ref(null);

// 返回上一页
const onClickLeft = () => {
  router.back();
};

// 注册 Vant 按钮组件
const components = {
  VanButton,
  VanNavBar,
};

// 获取当前日期并计算接下来七天的日期和星期
/**
 * 获取医生未来七天的排班信息和可预约状态
 * @param {string} workId - 医生的工号
 * @returns {Promise<Array>} 返回包含未来七天日期信息的数组，每个元素包含：
 *   - formattedDate: 格式化的日期（MM.DD）
 *   - weekday: 星期几
 *   - hasAvailableSlot: 是否有可预约时段
 */
const getDates = async (workId) => {
  const now = new Date();
  const dates = [];
  // 调用API获取医生未来七天的排班信息
  const scheduleRes = await getNextWeekSchedules(workId);
  if (!scheduleRes.success) {
    showToast(scheduleRes.errMsg || "获取排班信息失败");
    return [];
  }
  const schedules = scheduleRes.data;
  
  // 遍历未来七天，计算每天的日期信息和可预约状态
  for (let i = 0; i < 7; i++) {
    // 计算当前遍历日期
    const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000);
    // 格式化月份和日期，确保两位数显示
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const formattedDate = `${month}.${day}`;
    // 获取对应的星期文本
    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const weekday = weekdays[date.getDay()];
    
    // 获取当天的排班信息，判断是否有可预约时段
    // 从排班数据中获取当天的排班信息数组
    // schedules[i]包含了当天所有的时间段信息，如果没有排班则返回空数组
    const daySchedules = schedules[i] || [];
    // 判断当天是否有可预约的时间段
    // 遍历所有时间段，检查是否存在至少一个时间段的已预约数(bookedCount)小于最大预约数(maxBooking)
    // 如果找到任意一个符合条件的时间段，则该天可以预约
    const hasAvailableSlot = daySchedules.some(schedule => schedule.bookedCount < schedule.maxBooking);
    
    // 将当天的日期信息添加到结果数组
    dates.push({
      formattedDate,
      weekday,
      hasAvailableSlot
    });
  }
  return dates;
};

const dates = ref([]);

// 获取排班信息
const fetchSchedules = async (workId) => {
  dates.value = await getDates(workId);
};

// 预约逻辑
const bookAppointment = async (date, dateIndex) => {
  if (!userStoreAPI.isLogin) {
    router.push('/login/account');
    return;
  }

  if (date.hasAvailableSlot) {
    try {
      // 重新获取最新的排班信息
      const scheduleRes = await getNextWeekSchedules(doctor.value.id);
      if (!scheduleRes.success) {
        showToast(scheduleRes.errMsg || '获取排班信息失败');
        return;
      }
      
      // 获取选中日期的排班信息
      const daySchedules = scheduleRes.data[dateIndex] || [];
      if (daySchedules.length === 0) {
        showToast('当前日期暂无可用时段');
        return;
      }
      
      // 获取就诊人信息
      const res = await getPatientInfoAPI();
      if (res.success && res.data && res.data.length > 0) {
        patientList.value = res.data;
        // 保存排班信息用于后续选择时间段
        timeSlots.value = daySchedules.map(schedule => ({
          id: schedule.ruleId,
          time: `${schedule.startTime[0].toString().padStart(2, '0')}:${schedule.startTime[1].toString().padStart(2, '0')}-${schedule.endTime[0].toString().padStart(2, '0')}:${schedule.endTime[1].toString().padStart(2, '0')}`,
          remaining: schedule.maxBooking - schedule.bookedCount,
          price: schedule.price
        }));
        showPatientSelector.value = true;
      } else {
        showToast('暂无就诊人信息');
        router.push('/addPatient');
      }
    } catch (error) {
      console.error('获取信息失败:', error);
      showToast('获取信息失败');
    }
  }
};

// 选择就诊人
const selectPatient = (patient) => {
  selectedPatient.value = patient;
  showPatientSelector.value = false;
  showTimeSlots.value = true;
};

// 选择时间段
const selectTimeSlot = async (timeSlot) => {
  try {
    selectedTimeSlot.value = timeSlot;
    showTimeSlots.value = false;
    
    // 获取当前选中日期的日期字符串（YYYY-MM-DD格式）
    const selectedDate = new Date();
    selectedDate.setDate(selectedDate.getDate() + dates.value.findIndex(date => date.hasAvailableSlot));
    const scheduleDate = selectedDate.toISOString().split('T')[0];

    // 解析时间段字符串获取开始和结束时间
    const [startTimeStr, endTimeStr] = timeSlot.time.split('-');
    
    // 调用挂号API
    const bookingData = {
      workId: doctor.value.id,
      ruleId: timeSlot.id,
      medicalRecordNumber: selectedPatient.value.medicalRecordNumber,
      scheduleDate: scheduleDate,
      startTime: startTimeStr + ':00',
      endTime: endTimeStr + ':00',
      price: timeSlot.price,
      status: 1 // 1=已预约
    };
    
    const res = await bookingAPI(bookingData);
    if (res.success) {
      showToast('预约成功！');
      // 刷新排班信息
      await fetchSchedules(doctor.value.id);
    } else {
      showToast(res.errMsg || '预约失败，请稍后重试');
    }
  } catch (error) {
    console.error('预约失败:', error);
    showToast('预约失败，请稍后重试');
  }
};
const isFollowed = ref(false);
const doctor = ref({
  id: 1,
  avatar: "",
  name: "",
  title: "",
  department: "",
  intro: "",
});

// 获取医生详情信息
const fetchDoctorDetails = async () => {
  try {
    const workId = route.query.id;
    if (!workId) {
      showToast("医生ID不存在");
      return;
    }
    const res = await getDoctorByWorkId(workId);
    if (res.success) {
      doctor.value = {
        id: res.data.workId,
        avatar: res.data.imgUrl || "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg",
        name: res.data.doctorName,
        title: res.data.title,
        department: res.data.departmentName,
        intro: res.data.personalProfile || "暂无简介",
      };
    } else {
      showToast(res.errMsg || "获取医生信息失败");
    }
  } catch (error) {
    console.error("获取医生信息失败:", error);
    showToast("获取医生信息失败，请稍后重试");
  }
};

const followDoctor = async () => {
  try {
    if (!userStoreAPI.isLogin) {
      router.push('/login/account');
      return;
    }
    const userId = userStoreAPI.userInfo.id;
    if (!isFollowed.value) {
      const res = await addFollowAPI(userId, doctor.value.id);
      if (res.success) {
        doctorFollowStore.addFollowedDoctor(doctor.value);
        isFollowed.value = true;
        showToast('关注成功');
      } else {
        showToast(res.errMsg || '关注失败');
      }
    } else {
      const res = await deleteFollowAPI(userId, doctor.value.id);
      if (res.success) {
        doctorFollowStore.removeFollowedDoctor(doctor.value.id);
        isFollowed.value = false;
        showToast('已取消关注');
      } else {
        showToast(res.errMsg || '取消关注失败');
      }
    }
  } catch (error) {
    console.error('关注操作失败:', error);
    showToast('操作失败，请稍后重试');
  }
};

// 检查关注状态
const checkFollowStatus = async () => {
  try {
    const userId = userStoreAPI.userInfo.id;
    if (userId && doctor.value.id) {
      const res = await isFollowedAPI(userId, doctor.value.id);
      if (res.success) {
        isFollowed.value = res.data;
      }
    }
  } catch (error) {
    console.error('获取关注状态失败:', error);
  }
};

// 组件挂载时获取医生信息和排班信息
onMounted(async () => {
  await fetchDoctorDetails();
  if (doctor.value.id) {
    await fetchSchedules(doctor.value.id);
    await checkFollowStatus();
  }
});
</script>

<style scoped>

.schedule-table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
  margin-top: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.schedule-table th,
.schedule-table td {
  border: none;
  padding: 6px;
  text-align: center;
  background-color: #fff;
}

.schedule-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
}

.weekday {
  font-size: 10px;
  color: #666;
  margin-top: 2px;
  display: block;
}

.van-button {
  height: 28px;
  font-size: 12px;
  transition: all 0.3s ease;
  padding: 0 8px;
}

.schedule-table td {
  border-bottom: 1px solid #ebeef5;
}

.schedule-table tr:last-child td {
  border-bottom: none;
}

.weekday {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  display: block;
}

.van-button {
  height: 32px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.van-button--primary {
  background-color: #3498db;
  border-color: #3498db;
}

.van-button--primary:active {
  background-color: #2980b9;
  border-color: #2980b9;
}

.van-button--default {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #909399;
}

.appointment {
  padding: 15px;
  background-color: #fff;
  border-radius: 10px;
  margin-top: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.appointment h4 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}
.weekday {
  font-size: 10px;
}
.doctor-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f9f9f9; /* 新增背景颜色 */
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 新增阴影效果 */
}
.doctor-info img {
  width: 100px; /* 增大图片尺寸 */
  height: 100px;
  margin-right: 20px;
  border-radius: 50%; /* 图片圆形效果 */
}
.doctor-details h3 {
  margin: 0;
  font-size: 24px; /* 增大字体大小 */
  color: #333;
}
.doctor-details .department {
  /* color: #666; */
  margin-bottom: 10px;
  font-size: 16px;
}
.like-button {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease; /* 新增过渡效果 */
}
.like-button.liked {
  background-color: #c0392b;
}
.follow-button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
  transition: background-color 0.3s ease; /* 新增过渡效果 */
}
.follow-button.followed {
  background-color: #2980b9;
}
.follow-button.unfollowed {
  background-color: #e74c3c;
}
.doctor-intro {
  margin-bottom: 20px;
  font-size: 16px;
  color: #555;
}
.appointment h4 {
  margin-bottom: 10px;
  font-size: 20px;
  color: #333;
}
.appointment-date {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  background-color: #f4f4f4; /* 新增背景颜色 */
  padding: 10px;
  border-radius: 5px;
}
.appointment-date span {
  width: 120px;
  font-size: 16px;
  color: #333;
}
.appointment-time {
  display: flex;
}
.appointment-button {
  background-color: #ccc;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 10px;
  transition: background-color 0.3s ease; /* 新增过渡效果 */
}
.appointment-button.available {
  background-color: #2ecc71;
}

.patient-selector,
.time-slots {
  padding: 16px;
}

.popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.van-cell {
  margin-bottom: 8px;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.van-cell:active {
  background-color: #f0f0f0;
}
</style>
